package com.nervenets.shopping.controller.common.params;

import com.nervenets.general.aspect.validate.NotUrl;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.web.params.FormParams;
import com.nervenets.shopping.enumeration.Gender;
import com.nervenets.shopping.hibernate.domain.common.IdCard;
import com.nervenets.shopping.service.IdCardService;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class IdCardFormParams extends FormParams<IdCard, IdCardService> {
    @ApiModelProperty(value = "关联人ID", required = true)
    @Positive
    private long unionId;
    @ApiModelProperty(value = "姓名", required = true)
    @NotBlank
    private String name;
    @ApiModelProperty(value = "性别", required = true)
    @NotNull
    private Gender gender;
    @ApiModelProperty(value = "民族")
    private String nation;
    @ApiModelProperty(value = "生日", required = true)
    @Positive
    private long birthday;
    @ApiModelProperty(value = "地址", required = true)
    @NotBlank
    private String address;
    @ApiModelProperty(value = "身份证号码", required = true)
    @NotBlank
    private String number;
    @ApiModelProperty(value = "有效期开始")
    private long validStartTime;
    @ApiModelProperty(value = "有效期结束")
    private long validEndTime;
    @ApiModelProperty(value = "签发机构")
    private String signedOrgan;
    @ApiModelProperty(value = "正面图", required = true)
    @NotUrl
    private String frontImage;
    @ApiModelProperty(value = "背面图", required = true)
    @NotUrl
    private String backImage;

    @Override
    public IdCard validateAndBuild(IdCardService service, HttpServletRequest request, HttpServletResponse response) {
        IdCard idCard = super.validateAndBuild(service, request, response);
        if (service.hasUniqueKey(idCard.getId(), (predicates, root, criteriaQuery, criteriaBuilder) -> {
            predicates.add(criteriaBuilder.equal(root.get("unionId"), getUnionId()));
            predicates.add(criteriaBuilder.equal(root.get("name"), getName()));
        })) {
            throw new LogicException(String.format("已存在【%s】的身份证信息", idCard.getName()));
        }
        if (service.hasUniqueKey(idCard.getId(), (predicates, root, criteriaQuery, criteriaBuilder) -> {
            predicates.add(criteriaBuilder.equal(root.get("unionId"), getUnionId()));
            predicates.add(criteriaBuilder.equal(root.get("number"), getNumber()));
        })) {
            throw new LogicException(String.format("已存在【%s】的身份证信息", idCard.getNumber()));
        }
        return idCard;
    }
}
